package com.wish233.wiliwilivideo.mq;

import com.rabbitmq.client.Channel;
import com.wish233.wiliwilivideo.domain.po.VideoViewHistory;
import com.wish233.wiliwilivideo.service.VideoViewHistoryService;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.wish233.wiliwilicommon.constants.MqConstant.DLX_EXCHANGE;
import static com.wish233.wiliwilicommon.constants.MqConstant.DLX_ROUTING_KEY;
import static com.wish233.wiliwilicommon.constants.RedisConstants.COMMENT_CHILD_VIDEO_KEY;
import static com.wish233.wiliwilicommon.constants.RedisConstants.COMMENT_ROOT_VIDEO_KEY;
import static com.wish233.wiliwilivideo.domain.constant.AMQPConstant.*;

/**
 * @author WHH
 */
@Service
public class HistoryMessageListener {

    @Resource
    private VideoViewHistoryService videoViewHistoryService;


    @SneakyThrows
    @Transactional(rollbackFor = RuntimeException.class)
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = HISTORY_UPSERT_QUEUE, durable = "true", arguments = {
                            @Argument(name = "x-dead-letter-exchange", value = DLX_EXCHANGE), // 设置死信交换机
                            @Argument(name = "x-dead-letter-routing-key", value = DLX_ROUTING_KEY),
                            @Argument(name = "x-message-ttl", value = "300000", type = "java.lang.Long")// 设置死信路由键
                    }),
                    exchange = @Exchange(name = HISTORY_UPSERT_EXCHANGE),
                    key = HISTORY_UPSERT_ROUTING_KEY),
            ackMode = "MANUAL")
    public void handleCommentCache(VideoViewHistory videoViewHistory, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        boolean success = videoViewHistoryService.saveOrUpdate(videoViewHistory);
        if (success) {
            channel.basicAck(deliveryTag, false);
        } else {
            channel.basicNack(deliveryTag, false, true);
        }
    }


}
